import requests
import base64

# 配置信息
API_BASE = "https://api.siliconflow.cn/v1"
API_KEY = "sk-zkhhzzsrsjrdfyxxvhrjlpcrqwkuewczdsmajkguiqijoolj"
MODEL_NAME = "Pro/Qwen/Qwen2.5-VL-7B-Instruct"


def check_handwriting(image_path: str, target_char: str) -> dict:
    # 读取并编码图像
    with open(image_path, "rb") as f:
        image_b64 = base64.b64encode(f.read()).decode("utf-8")

    # 构造请求体
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": MODEL_NAME,
        "messages": [
            {
                "role": "system",
                "content": "你是一个汉字书写判别助手，需要判断用户提供的手写汉字图片是否与目标汉字匹配，并给出书写建议。"
            },
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": f"请判断以下手写汉字是否与目标字'${target_char}'匹配，并给出书写建议："},
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}}
                ]
            }
        ]
    }

    # 发送请求
    try:
        response = requests.post(f"{API_BASE}/chat/completions", json=payload, headers=headers)
        response.raise_for_status()
        result = response.json()
        return {
            "matched": "匹配" in result['choices'][0]['message']['content'],
            "suggestion": result['choices'][0]['message']['content']
        }
    except Exception as e:
        return {
            "error": f"API调用失败：{str(e)}",
            "details": response.text if 'response' in locals() else ""
        }


if __name__ == "__main__":
    image_path = "ta.png"  
    target_char = "他"
    result = check_handwriting(image_path, target_char)
    print("判别结果：", result)